package com.complaint.rest.web;

import com.complaint.rest.model.Complaint;
import com.complaint.rest.security.dto.ExampleUserDetails;
import com.complaint.rest.service.ComplaintService;
import com.complaint.rest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.Map;

/**
 * Created by Alex
 */
@Controller
public class MainController {
    @Autowired
    private UserService userService;

    @Autowired
    private ComplaintService complaintService;

    @RequestMapping("/index")
    public String listComplaints(Map<String, Object> map) {
        boolean authenticated = !"guest".equals(SecurityContextHolder.getContext().getAuthentication().getName());
        map.put("authenticated", authenticated);

        try {
            UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
            ExampleUserDetails user = (ExampleUserDetails) authentication.getPrincipal();
            map.put("mycomplaints", complaintService.getComplaintsByUserId(user.getId()));
        } catch (Exception e) {
            map.put("mycomplaints", new ArrayList<Complaint>());
        }

        map.put("allcomplaints", complaintService.listComplaints());
        return "index";
    }

    @RequestMapping("/")
    public String home() {
        return "redirect:/index";
    }
}
